﻿using ShopPowerTemplate.Commands;
using ShopPowerTemplate.Common;
using ShopPowerTemplate.Common.Authentication;
using ShopPowerTemplate.Entities;
using ShopPowerTemplate.WebServiceReference;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using Windows.Storage;
using Windows.System;
using Windows.UI.Popups;

namespace ShopPowerTemplate.ViewModels
{
    public class ConfirmOrderViewModel : BindableBase
    {
        private string _title;
        public virtual string Title
        {
            get
            {
                if (_title == null)
                    _title = "Confirmar pago";
                return _title;
            }
            set
            {
                this.SetProperty(ref this._title, value);
            }
        }

        bool isCompleted = false;
        public bool IsCompleted
        {
            get { return this.isCompleted; }
            set
            {
                this.SetProperty(ref this.isCompleted, value);
            }
        }

        string message = "Confirme el pago usando su navegador web para continuar...";
        public string Message
        {
            get { return this.message; }
            set
            {
                this.SetProperty(ref this.message, value);
            }
        }

        public ConfirmOrderViewModel()
        {

        }

        public async void ConfirmOrder()
        {
            if (App.ShoppingCart.Validate())
            {
                try
                {
                    Order order = new Order
                    {
                        Date = DateTime.Now,
                        ShippingCost = App.ShoppingCart.ShippingCost
                    };

                    foreach (CartItem item in App.ShoppingCart.CartList)
                    {
                        OrderDetail orderDetail = new OrderDetail
                        {
                            Order = order,
                            Price = item.ProductPresenter.Product.Price,
                            ProductDetail = item.ProductDetail,
                            Quantity = item.ItemsCount,
                            Tax = item.ProductPresenter.Product.Tax,
                            Discount = item.ProductPresenter.Product.Discount
                        };
                        order.OrderDetails.Add(orderDetail);
                    }

                    //Save order
                    WebServiceAuthenticatedClient service = new WebServiceAuthenticatedClient();
                    order = await service.AddOrderAsync(order);

                    //Clear the shopping cart
                    App.ShoppingCart.Clear();

                    //Get PayPal checkout url
                    string checkoutUrl = await service.GetPaypalCheckOutUrlAsync(order);
                    await Launcher.LaunchUriAsync(new Uri(checkoutUrl));

                    //Wait while user pays through PayPal
                    while (order.OrderState.Id == (int)OrderStateEnum.NuevoPedido)
                    {
                        await Sleep(5000);
                        order = await service.FindOrderAsync(order.Id);
                    }

                    bool isConfirmed = order.OrderState.Id == (int)OrderStateEnum.PendienteDePago;
                    Message = isConfirmed ? "Su pedido se ha recibido con éxito." : "Su pedido ha sido cancelado.";
                }
                catch
                {
                    Message = "No hemos podido procesar su pedido. Inténtelo más tarde";
                }
                finally
                {
                    IsCompleted = true;
                }
            }
        }

        static async Task Sleep(int ms)
        {
            await Task.Delay(ms);
        }
    }
}
